package cn.findviewbydream.evil.app.test;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import javax.servlet.http.HttpSession;
import java.util.Map;

/********************************************
 * 工程名：MealOrder
 * 包名：cn.findviewbydream.evil.app.test
 * 时间：16-12-19
 * 作者：白雨濃 evil
 * 邮箱：evilbai@foxmail.com
 * 内容：握手拦截器
 ********************************************/
public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor
{
    /**
     * 握手之前
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler
            wsHandler, Map<String, Object> attributes) throws Exception
    {
        if (request instanceof ServletServerHttpRequest)
        {
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
            HttpSession session = servletRequest.getServletRequest().getSession(false);
            System.out.println(session);
            if (session != null)
            {
                //使用userName区分WebSocketHandler，以便定向发送消息
                String userName = (String) session.getAttribute("user");
                System.out.println(userName);
                attributes.put("WEBSOCKET_USERID", userName);
            }
        }
        return true;
    }

    /**
     * 握手之后
     */
    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
                               Exception ex)
    {
        super.afterHandshake(request, response, wsHandler, ex);
    }
}
